#include "PinRefParser.h"

#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

PinRefParser::PinRefParser(
    QStringParser *&_componentRefParser
    , QStringParser *&_pinParser
    , QStringParser *&_titleParser
):    m_componentRefParser(_componentRefParser)
    , m_pinParser(_pinParser)
    , m_titleParser(_titleParser)
{

}

bool PinRefParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new PinRef());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("componentRef")))
    {
        data = reader->attributes().value(QStringLiteral("componentRef"));
        if (!m_componentRefParser->parse(reader, data))
            return false;
        m_result->componentRefOptional = Optional<QString>(m_componentRefParser->result());
    }
    if (reader->attributes().hasAttribute(QStringLiteral("pin")))
    {
        data = reader->attributes().value(QStringLiteral("pin"));
        if (!m_pinParser->parse(reader, data))
            return false;
        m_result->pin = m_pinParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("pin: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("title")))
    {
        data = reader->attributes().value(QStringLiteral("title"));
        if (!m_titleParser->parse(reader, data))
            return false;
        m_result->titleOptional = Optional<QString>(m_titleParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

PinRef *PinRefParser::result()
{
    return m_result.take();
}

}